import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { getToken } from './utils/auth'
import { Message } from 'element-ui'
import store from './store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login']

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  const token = getToken()
  // 判断是否存在token没有白名单，放行
  if (token) {
    whiteList.includes(to.path) ? next('/') : next()
    // 放行后触发用户信息请求 但是登录后只需要触发一次信息请求
    !store.getters.userId && store.dispatch('user/navbarUsers')
    NProgress.done()
    return
  }
  // 判断如果有白名单也行  没有token也没有白名单就提示用户 重定向到登录页
  if (whiteList.includes(to.path)) {
    next()
    NProgress.done()
    return
  } else {
    NProgress.done()
    Message.info('请先登录')
    next('/login')
    return
  }
  // determine whether the user has logged in
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
